from PyQt5.Qt import *
from PyQt5.QtCore import QThread
from PyQt5.uic import loadUi
from datetime import datetime
from socket import socket, AF_INET, SOCK_DGRAM
import threading

server_ip_port = ('127.0.0.1', 9001)
buffer_size = 1024

msg_list = []


def format_msg(recv_code, msg, user_code):
    data = {
        "recv_code": recv_code,
        "msg": msg,
        "send_code": user_code,
        "date": str(datetime.now())
    }
    return str(data).encode('utf-8')


udp_client = socket(AF_INET, SOCK_DGRAM)

# QLabel

class Talk(QWidget):
    def __init__(self):
        super().__init__()
        # self.user_code = '0001'
        loadUi('client.ui', self)
        self.set_ui()
        # self.first_connect()

    def set_ui(self):
        self.lineEdit.setText('0002')
        self.pushButton.clicked.connect(self.send_msg)

        self.pushButton_2.clicked.connect(self.first_connect)

        self.thread = Runthread()

        self.thread._signal.connect(self.c)

        self.thread.start()
        # print('1232131')

    def c(self, res):
        cursor1 = self.textEdit.textCursor()
        cursor1.movePosition(QTextCursor.End)
        cursor1.insertHtml(res)

    def first_connect(self):
        self.user_code = self.lineEdit_2.text()
        data = {
            'code': self.user_code
        }
        udp_client.sendto(str(data).encode('utf-8'), server_ip_port)
        self.pushButton_2.setEnabled(False)
        self.pushButton.setEnabled(True)
        self.label.clear()
        self.label.setText('当前登录用户：{}'.format(self.user_code))
        self.label.adjustSize()
        # QPushButton

    def send_msg(self):
        # QTextEdit
        target_code = self.lineEdit.text()
        # print('发送消息到,', target_code)
        send_msg = self.textEdit_2.toPlainText()
        self.user_code = self.lineEdit_2.text()

        msg_data = format_msg(target_code, send_msg, self.user_code)
        msg_list.append(eval(msg_data.decode('utf-8')))
        udp_client.sendto(msg_data, server_ip_port)
        data = eval(msg_data.decode('utf-8'))
        # res = '''\r%s %s
        #         \r%s
        #         \r-------------------------------\n
        # ''' % (data.get('send_code'), data.get('date'), data.get('msg'))
        res = '''
        <p style="color:red;">
          <span>{}（我）:{}</span>
        </p>
        <p>{}</p><br>
        '''.format(data.get('send_code'), data.get('date'), data.get('msg'))
        cursor1 = self.textEdit.textCursor()
        cursor1.movePosition(QTextCursor.End)
        cursor1.insertHtml(res)
        self.textEdit_2.clear()


class Runthread(QThread):
    # 定义信号,定义参数为str类型
    _signal = pyqtSignal(str)

    def __init__(self, parent=None):
        super(Runthread, self).__init__()
        # print('111')

    def run(self):
        # print(222)
        while True:
            try:
                data, addr = udp_client.recvfrom(1024)
            except:
                data = []
            # print(data.decode('utf-8'))
            if len(data) > 0:
                data = eval(data.decode('utf-8'))
                # msg_list.append(data)
                res = '''
                <p style="color:blue;">
                  <span>{}:{}</span>
                </p>
                <p>{}</p><br>
                '''.format(data.get('send_code'), data.get('date'), data.get('msg'))
                # res = '''\r%s %s
                # \r%s
                # \r-------------------------------
                # ''' % (data.get('send_code'), data.get('date'), data.get('msg'))
                # print('333333:', res)
                self._signal.emit(res)


if __name__ == '__main__':
    app = QApplication([])
    t = Talk()
    t.show()
    app.exec_()
